package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vo.WmNewsVo;
import com.heima.utils.thread.WeMediaThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 文章列表分页条件查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findByPage(WmNewsPageReqDto dto) {
        //1.校验参数

        if (dto == null)
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        dto.checkParam();

        //2.构建分页条件构造器

        Page page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaQuery();
        //2.1匹配状态
        if (dto.getStatus() != null)
            wrapper.eq(WmNews::getStatus,dto.getStatus());

        //2.2匹配频道id
        if (dto.getChannelId() != null)
            wrapper.eq(WmNews::getChannelId,dto.getChannelId());

        //2.3匹配关键字
        if (dto.getKeyword() != null)
            wrapper.like(WmNews::getTitle,dto.getKeyword());

        //2.4匹配开始结束时间
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null)
            wrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());

        wrapper.orderByDesc(WmNews::getCreatedTime);

        //3.查询数据库
        page(page,wrapper);

        //4.封装结果返回
        PageResponseResult result = new PageResponseResult((int)page.getCurrent(),(int)page.getSize(),(int)page.getTotal());
        result.setCode(AppHttpCodeEnum.SUCCESS.getCode());
        result.setErrorMessage(AppHttpCodeEnum.SUCCESS.getErrorMessage());
        result.setData(page.getRecords());

        return result;
    }

    /**
     * 发布文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submit(WmNewsDto dto) {
        //校验参数
        if (dto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        //数据处理
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);

        //封面图片 images    list---> string
        if (dto.getImages() != null && dto.getImages().size() > 0){
            String images = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(images);
        }

        //文章封面图片布局 type
        if (dto.getType() == -1){
            wmNews.setType(null);    //针对-1,先置为null,后续再处理
        }


        //1.根据ID判断:新增/修改文章
        saveOrUpdateNews(wmNews);


        //2.判断是否为草稿,是草稿就直接返回结果,流程结束
        if (dto.getStatus() == 0){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //3.不是草稿,需要处理内容图片和文章的关联关系
        //提取文章内容中的所有图片
        List<String> imageUrls = parseImageURL(dto.getContent());
        saveRelationWithContentImage(imageUrls,wmNews.getId());


        //4.不是草稿,需要处理封面图片和文章的关联关系
        saveRelationWithCoverImage(dto,wmNews,imageUrls);


        //5. 发布完成后，异步添加任务：定时审核文章
        wmNewsTaskService.addNewsToTask(wmNews.getId(),dto.getPublishTime());



        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 文章上下架
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.检查参数
        if (dto.getId() == null || dto.getEnable() == null || (dto.getEnable() != 0 && dto.getEnable() != 1)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        //3.判断文章是否已发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章不是发布状态，不能上下架");
        }

        //4.修改文章enable
        update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable, dto.getEnable())
                .eq(WmNews::getId, wmNews.getId()));

        //5. 发送消息，通知article端修改文章配置
        if(wmNews.getArticleId() != null){
            Map<String,Object> map = new HashMap<>();
            map.put("articleId",wmNews.getArticleId());
            map.put("enable",dto.getEnable());
            kafkaTemplate.send(WemediaConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult findOne(Integer id) {
        //1.检查参数
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.结果返回
        return ResponseResult.okResult(wmNews);
    }

    /**
     * 查询文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        //1.参数检查
        dto.checkParam();

        //记录当前页
        int currentPage = dto.getPage();

        //2.分页查询+count查询
        dto.setPage((dto.getPage()-1)*dto.getSize());
        List<WmNewsVo> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        int count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(currentPage,dto.getSize(),count);
        responseResult.setData(wmNewsVoList);
        return responseResult;
    }


    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1.检查参数
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3.查询用户信息
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());

        //4.封装vo返回
        WmNewsVo vo = new WmNewsVo();
        //属性拷贝
        BeanUtils.copyProperties(wmNews,vo);
        if(wmUser != null){
            vo.setAuthorName(wmUser.getName());
        }

        ResponseResult responseResult = new ResponseResult().ok(vo);

        return responseResult;
    }


    /**
     * 文章审核，修改状态
     * @param status  2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDto dto) {
        //1.检查参数
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3.修改文章的状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);

        //审核成功，则需要创建app端文章数据，并修改自媒体文章
        if(status.equals(WemediaConstants.WM_NEWS_AUTH_PASS)){
            //创建app端文章数据
            ResponseResult responseResult = wmNewsAutoScanService.saveAppArticle(wmNews);
            if(responseResult.getCode().equals(200)){
                wmNews.setArticleId((Long) responseResult.getData());
                wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
                updateById(wmNews);
            }
        }

        //4.返回
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存封面图片和文章关系
     * 核心功能1:
     *    如果封面模式为自动,需要按规则匹配对应的封面到底是单图还是多图,还是无图.匹配规则:
     *    a.如果内容图片数量 >= 1 && 如果内容图片数量 < 3, 单图模式, setType(1)
     *    b.如果内容图片数量 >= 3, 多图模式, setType(3)
     *    c.如果内容图片数量 == 0, 无图模式, setType(0)
     *
     * 核心功能2:
     *    保存封面图片和文章的关联关系
     *
     * @param dto          前端传过来的文章数据
     * @param wmNews       存入数据中的文章数据
     * @param imageUrls    当前文章内容中的所有图片
     */
    private void saveRelationWithCoverImage(WmNewsDto dto, WmNews wmNews, List<String> imageUrls) {

        //拿到前端传过来的封面图片数据
        List<String> images = dto.getImages();

        //1.处理封面图片为自动的情况
        if (dto.getType() == WemediaConstants.WM_NEWS_TYPE_AUTO){
            if (imageUrls.size() >= 3){
                //多图
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                //将内容图片中的前三张截取作为封面图片
                images = imageUrls.stream().limit(3).collect(Collectors.toList());
            }else if (imageUrls.size() >= 1 && imageUrls.size() < 3){
                //单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                //将内容图片截取作为封面图片
                images = imageUrls.stream().limit(1).collect(Collectors.toList());
            }else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            //处理数据库中要保存的封面图片路径
            if (images != null && images.size() > 0){
                wmNews.setImages(StringUtils.join(images,","));
            }

            //修改数据库中的文章的封面类型
            updateById(wmNews);
        }

        //2.保存封面图片和文章的关联关系
        if (images != null && images.size() > 0){
            saveRelationWithImage(images,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);
        }

    }

    /**
     * 保存文章与内容图片关系
     * @param imageUrls
     * @param id
     */
    private void saveRelationWithContentImage(List<String> imageUrls, Integer id) {
        saveRelationWithImage(imageUrls,id, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    /**
     * 保存文章与素材图片的关联关系
     * @param imageUrls
     * @param newsId
     * @param type
     */
    private void saveRelationWithImage(List<String> imageUrls, Integer newsId, Short type) {
        //校验参数
        if (imageUrls != null && newsId != null){
          //1.根据图片url查询素材表,拿到图片的id  select * from wm_
            List<WmMaterial> dbMaterials = wmMaterialMapper
                    .selectList(Wrappers.<WmMaterial>lambdaQuery()
                    .in(WmMaterial::getUrl, imageUrls));
            List<Integer> materialIds = dbMaterials.stream()
                    .map(wmMaterial -> wmMaterial.getId())
                    .collect(Collectors.toList());
            if (materialIds.size() != imageUrls.size()){
                //如果数据库中图片数量与内容中提取到的图片数量不对应,说明内容图片有脏数据
                //这时要排除异常,将整个业务数据回滚
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }

            //2.保存图片素材与文章的关联关系
            wmNewsMaterialMapper.saveRelations(materialIds,newsId,type);

        }
    }

    /**
     * 提取文章内容图片
     * @param content
     * @return
     */
    private List<String> parseImageURL(String content){
        JSONArray jsonArray = JSON.parseArray(content);

        List<String> list = new ArrayList<>();

        //遍历集合,取出每一个数据
        for (Object json : jsonArray){
            JSONObject jsonObject = JSON.parseObject(json.toString());
            //判断type是否为image
            if (jsonObject.get("type").equals("image")){
                //是image,则取当前json的value
                String imageUrl = jsonObject.get("value").toString();
                list.add(imageUrl);
            }
        }
        return list;
    }




    /**
     * 新增或修改文章
     * @param wmNews
     */
    private void saveOrUpdateNews(WmNews wmNews){
        //设置修改时间为当前时间
        wmNews.setSubmitedTime(new Date());

        if (wmNews.getId() != null){
            //修改
            //先删除当前文章与素材的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            if (wmNews.getUserId() == null){
                wmNews.setUserId(WeMediaThreadLocalUtil.get());
            }
            updateById(wmNews);
        }else {
            //新增
            //处理数据:userId, createTime, submitTime
            wmNews.setUserId(WeMediaThreadLocalUtil.get());
            wmNews.setCreatedTime(new Date());
            save(wmNews);
        }
    }
}
